<?php
namespace api\zmt\controller;



use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use api\zmt\model\CodeModel;

use api\zmt\model\RegistrationModel;
use api\zmt\validate\registrationValidate;
use cmf\controller\RestBaseController;
use Darabonba\OpenApi\Models\Config;


class registrationController extends RestBaseController
{
    public function registration(){
       $data = input('post.');
       if (empty($data)){
           return json(['code'=>0,'msg'=>'数据不全请重新添加','data'=>$data]);
       }
       $exit = RegistrationModel::where('mobile',$data['mobile'])->find();
       if ($exit){
           return json(['code'=>0,'msg'=>'你的手机号已存在，请重新提交手机号','data'=>null]);
       }

       if (!checkSmsCode($data['mobile'],$data['code'])){
           return error('验证码失效或已过期');
       }
       $validate = new registrationValidate();
       if (!$validate->scene('registration')->check($data)){
           return error($validate->getError());
       }
       $salt = RandStar();
       $password = $data['password'].$salt;
       $data['salt'] = $salt;
       $data['password']=md5($password);
       $data['create_time']=time();
       $model = RegistrationModel::create($data);
       if ($model){
           return success('创建成功请登录');
       }else{
           return error('创建失败请重新创建');
        }
    }

    public function sendAliSms()
    {
        $code = mt_rand(1111, 9999);
        $mobile = input('mobile');
        $config = new Config([
            // 从阿里云获取
            'accessKeyId' => config('app.aliSms.accessKeyId'),
            'accessKeySecret' => config('app.aliSms.accessKeySecret'),
        ]);

        $config->endpoint = "dysmsapi.aliyuncs.com";
        $client = new Dysmsapi($config);

        // 运行时参数超时设置，仅对使用了该运行时参数实例的请求有效
        $runtimeOptions = new RuntimeOptions();
        // true 忽略证书校验
        $runtimeOptions->ignoreSSL = true;

        $sendSmsRequest = new SendSmsRequest();
        // 手机号
        $sendSmsRequest->phoneNumbers = $mobile;
        // 签名名称
        $sendSmsRequest->signName = '阿里云短信测试';
        // 模板CODE
        $sendSmsRequest->templateCode = 'SMS_154950909';
        // 生成随机数作为验证码
        $sendSmsRequest->templateParam = json_encode(['code' => $code]);
        try {
            $response = $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
        } catch (\Exception $exception) {
            halt($exception->getMessage());
        }
        if ($response->body->code == 'OK') {
            echo '短信发送成功！';
            $data = [
                'mobile' =>$mobile,
                'code' =>$code,
                'send_time'=>time(),
            ];
            $model = CodeModel::create($data);
            if ($model){
                return success('存储成功');
            }
        } else {
            halt($response->body->message);
        }

    }
}